/*
 * Copyright 2003-2005 (c) Live Media Pty Ltd. <argot@einet.com.au> 
 *
 * This software is licensed under the Argot Public License 
 * which may be found in the file LICENSE distributed 
 * with this software.
 *
 * More information about this license can be found at
 * http://www.einet.com.au/License
 * 
 * The Developer of this software is Live Media Pty Ltd,
 * PO Box 4591, Melbourne 3001, Australia.  The license is subject 
 * to the law of Victoria, Australia, and subject to exclusive 
 * jurisdiction of the Victorian courts.
 */

#include "Types.h"

#include "TypeHelper.h"

#include "util/buffer.h"
#include "meta/MetaDefinition.h"


type_buffer * type_helper_resolve_structure( reference_type_map * refMap, type_element * definition )
{
	int rc;
	type_buffer * buffer = type_malloc( sizeof( type_buffer ) );
	buffer->data = (char * ) type_malloc( 1024 );
	buffer->size = 1024;
	buffer_data writer_data;	
	type_output_stream tmos;
	
	buffer_data_init( &writer_data, buffer->data, buffer->size );
	type_output_init( &tmos, &refMap->map, &bufferWriter, &writer_data );

	rc = type_output_write_named_object( &tmos, &meta_definition_name, definition );
	if ( rc != TYPE_OK ) return NULL;
	
	type_output_destroy( &tmos );
	
	buffer->size = writer_data.pos;
	return buffer;			
}

bool type_helper_structure_matches( reference_type_map * coreMap, type_element * definition1, type_buffer * definition2 )
{
	type_buffer * struct1 = type_helper_resolve_structure( coreMap, definition1 );
	if ( struct1 == NULL ) return false;

	if ( struct1->size != definition2->size ) return false;
	
	if ( 0 != memcmp( struct1->data, definition2->data, definition2->size ))
	{
		type_free( struct1->data );
		type_free( struct1 );
		return false;
	}
	
	type_free( struct1->data );
	type_free( struct1 );
	return true;	
}

	
bool type_helper_element_matches( reference_type_map * core, type_element * definition1, type_element * definition2 )
{
	bool ret = true;
	
	type_buffer * struct1 = type_helper_resolve_structure( core, definition1 );
	if ( struct1 == NULL )
	{
		type_free( struct1->data );
		type_free( struct1 );
		return false;
	}
	
	
	type_buffer * struct2 = type_helper_resolve_structure( core, definition2 );	
	if ( struct2 == NULL )
	{
		type_free( struct1->data );
		type_free( struct1 );
		type_free( struct2->data );
		type_free( struct2 );
		return false;
	}

	if ( struct1->size != struct2->size ) 
	{
		ret = false;
	}
	
	if ( ret && memcmp( struct1->data, struct2->data, struct1->size ) )
	{
		ret = false;
	}

	type_free( struct1->data );
	type_free( struct1 );
	type_free( struct2->data );
	type_free( struct2 );
	return ret;
}



